package com.shawn.springboot.integeration.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.shawn.springboot.integeration.common.constant.UserConstants;
import com.shawn.springboot.integeration.common.enums.UserStatus;
import com.shawn.springboot.integeration.system.model.pojo.SysUser;
import com.shawn.springboot.integeration.system.service.ISysLoginService;
import com.shawn.springboot.integeration.system.service.ISysPasswordService;
import com.shawn.springboot.integeration.system.service.ISysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author shawn
 * @description: 登录接口实现
 * @date 2022/9/1
 */
@Service
public class SysLoginServiceImpl implements ISysLoginService {

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysPasswordService passwordValidateService;

    @Override
    public SysUser login(String username, String password) {

        // 用户名或密码为空校验
        if(StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            throw new RuntimeException("用户名或密码为空");
        }

        // 密码长度校验
        if(password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new RuntimeException("密码长度不符合规范");
        }

        // 用户名长度校验
        if(username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new RuntimeException("用户名长度不符合规范");
        }

        // 查询用户信息
        SysUser sysUser = sysUserService.selectUserByLoginName(username);

        if(null == sysUser) {
            throw new RuntimeException("用户不存在");
        }

        // 检查账号是否被删除
        if(UserStatus.DELETED.getCode().equals(sysUser.getDelFlag())) {
            throw new RuntimeException("账号已被删除");
        }

        // 检查账号是否被停用
        if(UserStatus.DISABLE.getCode().equals(sysUser.getStatus())) {
            throw new RuntimeException("账号已被锁住");
        }

        // 密码校验
        passwordValidateService.validate(sysUser,password);

        return sysUser;
    }
}
